<?php

namespace app\db;

use think\db\Query;
use think\facade\Db;

class MyQuery extends  Query
{
    public function batchUpdate(array $data, string $idField = 'id'):bool
    {
        if (empty($data)) return false;  
        $table=$this->getTable();
        // 提取更新字段（排除主键）  
        $fields = array_filter(array_keys($data[0]), fn($k) => $k !== $idField);  
        // 构建每个字段的 CASE WHEN 语句  
        $cases = [];  
        $ids = [];  
        foreach ($fields as $field) {  
            $case = "$field = CASE $idField";  
            foreach ($data as $row) {  
                $id = (int)$row[$idField];  
                $value = is_string($row[$field]) ? "'" . addslashes($row[$field]) . "'" : $row[$field];  
                $case .= " WHEN $id THEN $value";  
                $ids[] = $id;  
            }  
            $case .= " END";  
            $cases[] = $case;  
        }  
        // 去重主键值  
        $ids = array_unique($ids);  
        // 拼接完整 SQL  
        $sql = "UPDATE $table  
                SET \n    " . implode(",\n    ", $cases) . "  
                WHERE $idField IN (" . implode(', ', $ids) . ");";  
        return Db::execute($sql);
    }
}